<template>
  <div class="takephoto">
  	<yd-navbar class="photoNav" bgcolor="rgba(255,255,255,0)">
        <router-link to="/" slot="left">
            <yd-navbar-back-icon class="faceText" color="#fff">人脸识别</yd-navbar-back-icon>
        </router-link>
    </yd-navbar>
    <div class="takephoto-model">
      <div class="photoText">请把面部放在人像框内</div>
      <img class="imgWrap" src="../assets/photoWrap.png">
      <video
          id="webcam"
          :style="videoStyle"
          :width="videoWidth"
          :height="videoHeight"
          loop
          preload>
      </video>
      <img
          :src="imgSrc"
          :style="imgStyle"
          class="face-img"
          v-if="imgSrc"/>
      <div class="photoBtns">
        <span class="photoBtnWrap"></span>
        <span class="photoBtn" @click="takePhoto"></span>
      </div>
    </div>
  </div>
</template>

<script>
import noiseImg from "../assets/noise.gif";
import URL from "../until/urlConfig.js"
export default {
  name: 'myfllow',
  data(){
  	return{
  		videoWidth: window.innerWidth,
  		videoHeight:window.innerHeight,
  		videoStyle: {
	        backgroundImage: "url(" + noiseImg + ")"
      	},
      	videoShow:null,
      	imgSrc: null,
      	canvas: null,
  		intervalId: null,
      	mediaStreamTrack: null,
  	}
  },
  components: {
  },
  methods:{
  	initVideo() {
      let that = this;
      // this.video = document.getElementById("face-result");
      this.videoShow = document.getElementById("webcam");
      // this.video.setAttribute('width', that.videoWidth);
      // this.video.setAttribute('height', that.videoHeight);
      this.canvas = document.createElement("canvas");
      this.canvas.setAttribute("width", this.videoWidth);
      this.canvas.setAttribute("height", this.videoHeight);
      this.imgStyle = {
        width: that.videoWidth + "px",
        height: that.videoHeight + "px"
      };
      setTimeout(() => {
        if (
          navigator.mediaDevices.getUserMedia ||
          navigator.getUserMedia ||
          navigator.webkitGetUserMedia ||
          navigator.mozGetUserMedia
        ) {
          //调用用户媒体设备, 访问摄像头
          // this.$toast.center("width:" + this.videoWidth);
          // this.$toast.center("height:" + this.videoHeight);
          this.getUserMedia(
            {
              video: {
                width: {
                  ideal: that.videoWidth
                  // max: that.videoWidth
                  // ideal: that.videoWidth,
                },
                height: {
                  ideal: that.videoHeight
                  // max: that.videoHeight
                  // ideal: that.videoHeight,
                },
                facingMode: "user",
                frameRate: {
                  ideal: 30,
                  min: 10
                }
              }
            },
            this.videoSuccess,
            this.videoError
          );
          // this.$toast.center("初始化摄像头打开失败：navigator is  not null");
        } else {
          	this.$dialog.toast({
		        mes: '摄像头打开失败,请检查权限设置!',
		        timeout: 1500
	    	});
          	// this.$toast.center("初始化摄像头打开失败：navigator is null");
        }
      }, 300);
    },
    takePhoto() {
      if (this.canvas) {
        let context = this.canvas.getContext("2d");
        context.drawImage(
          this.videoShow,
          0,
          0,
          this.videoWidth,
          this.videoHeight
        );
        console.log(context)
        this.imgSrc = this.canvas.toDataURL("image/png");
        // let imgData = this.canvas.toDataURL().substring(22);
        // console.log(imgData);
        // this.getAccessToken(imgData);

        let that = this;
        // that.faceFunction = "识别中...";
        let base64Data = this.canvas.toDataURL();
        let blob = this.dataURItoBlob(base64Data);
        console.log(blob);
        var file = new FormData();
        file.append("file", blob);
        file.append("key", that.uuid);
        console.log(file);
        this.axios
          .post(URL.baiduAI, file, {
            headers: {
              "Content-Type": "multipart/form-data"
            }
          })
          .then(function(response) {
            if ((response.status = 200)) {
              if (response.data.code == "200") {
                that.faceFunction = "点击识别";
                var result = response.data.data;
                result.forEach(item => {
                  item.beauty = Math.ceil(item.beauty);
                  if (!item.recommend) {
                    item["recommend"] = ["美的我都看不见你了"];
                  }
                  if (!item.face) {
                    item["face"] = "暂无推荐";
                  }
                });
                that.faceResult = result;
                that.imgSrc = null;
              } else {
                var failed = {
                  age: "未知",
                  beauty: "未知",
                  recommend: ["美的我都看不见你了"],
                  sex: "不知男女",
                  face: "暂无推荐"
                };
                that.faceResult = [failed];
                that.faceFunction = "点击识别";
                that.imgSrc = null;
              }
            } else {
              that.faceResult = [failed];
              that.faceFunction = "点击识别";
              that.imgSrc = null;
            }
          })
          .catch(function(error) {
            console.error(error);
            that.imgSrc = null;
            that.faceResult = [failed];
            that.faceFunction = "点击识别";
          });
      } else {
        that.imgSrc = null;
        this.$dialog.toast({
	        mes: '摄像未加载完成',
	        timeout: 1500
    	});
      }
    },
    //base64转换为Blob
    dataURItoBlob(base64Data) {
      var byteString;
      if (base64Data.split(",")[0].indexOf("base64") >= 0)
        byteString = atob(base64Data.split(",")[1]);
      else byteString = unescape(base64Data.split(",")[1]);
      var mimeString = base64Data
        .split(",")[0]
        .split(":")[1]
        .split(";")[0];
      var ia = new Uint8Array(byteString.length);
      for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
      }
      return new Blob([ia], { type: mimeString });
    },
    getUserMedia(constraints, success, error) {
      if (navigator.mediaDevices.getUserMedia) {
        //最新的标准API
        navigator.mediaDevices
          .getUserMedia(constraints)
          .then(success)
          .catch(error);
      } else if (navigator.webkitGetUserMedia) {
        //webkit核心浏览器
        navigator.webkitGetUserMedia(constraints, success, error);
      } else if (navigator.mozGetUserMedia) {
        //firfox浏览器
        navigator.mozGetUserMedia(constraints, success, error);
      } else if (navigator.getUserMedia) {
        //旧版API
        navigator.getUserMedia(constraints, success, error);
      }
    },
    videoSuccess(stream) {
      this.mediaStreamTrack = stream;
      this.videoShow.srcObject = stream;
      this.videoShow.play();
      // setTimeout(() => {
      //   this.takePhoto();
      // }, 150);
    },
    videoError(error) {
      	console.error(error);
      	this.$dialog.toast({
	        mes: '摄像头打开失败,请检查权限设置!',
	        timeout: 1500
    	});
    },
  },
  mounted(){
  	this.initVideo();
  	this.uuid = localStorage.getItem("uuid");
  }
}
</script>
<style lang="scss" scoped>
@import "../style/public.scss";
	.takephoto{
		.photoNav{
			position:absolute;
			z-index:5;
			width:100%;
			.faceText{
				color:#fff;
				font-size:rem(32);
			}
		}
		.photoText{
			position:absolute;
			top:rem(400);
			z-index:6;
			width:100%;
			color:#fff;
			text-align:center;
			font-size:rem(32);
		}
		.face-img{
			position:absolute;
			top:0;
			left:0;
			z-index:6;
		}
		.imgWrap{
			position:absolute;
			top:0;
			left:0;
			width:100%;
		}
		.photoBtns{
			position:absolute;
			bottom:rem(100);
			text-align:center;
			width:100%;
			height:rem(130);
			z-index:6;
			line-height:rem(130);
			.photoBtnWrap{
				position:absolute;
				display:inline-block;
				height:rem(130);
				width:rem(130);
				left:50%;
				background:rgba(255,255,255,.2);
				transform:translateX(-50%);
				border-radius:50%;
			}
			.photoBtn{
				position:absolute;
				display:inline-block;
				height:rem(100);
				width:rem(100);
				left:50%;
				transform:translate(-50%,rem(15));
				background:#fff;
				border-radius:50%;
			}
		}
	}
</style>
